from turbogears import *
from turbogears import identity, validators

import blockarticle.model as model
import blockarticle.article_view as article_view

class ArticleManager(identity.SecureResource):
    
    
    # Only admin can access this page
    require = identity.in_group('admin')
    
    @expose(template="blockarticle.templates.articlemanager.index")
    def index(self):
        import time
        Articles = model.Article.select()
        # log.debug("Happy TurboGears Controller Responding For Duty")
        return dict(articles=Articles)
    
    @expose(template="blockarticle.templates.articlemanager.articles")
    def reload(self):
        """Reload the articles"""
        Articles = model.Article.select()
        return dict(articles=Articles)
    
    @expose(template="blockarticle.templates.articlemanager.articles")
    def newarticle(self, title):
        """New a article
        
        @param title: Title of new article 
        """
        model.createArticle(title)
        Articles = model.Article.select()
        return dict(articles=Articles)
    
    @expose(template="blockarticle.templates.articlemanager.articles")
    def delete(self, id):
        """Delete a article"""
        ArticleID = int(id)
        Article = model.Article.get(ArticleID)
        Article.deleteArticle()
        Articles = model.Article.select()
        return dict(articles=Articles)
    
    @expose(template="blockarticle.templates.articlemanager.articles")
    def publish(self, id):
        """Publish article
        
        @param id: id of article to publish 
        """
        import kid
        
        ArticleID = int(id)
        ArticleView = article_view.ArticleView(ArticleID)
        
        Dictionary = {}
        Dictionary['article_header'] = ArticleView.RenderHeader()
        Dictionary['article_content'] = ArticleView.Render()
        Dictionary['article'] = ArticleView.Article
        Template = kid.Template(file="blockarticle/templates/article/index.kid", **Dictionary)
        
        ArticleFile = open('article.htm', 'wt')
        ArticleFile.write(Template.serialize(fragment=1, output='xhtml-strict', format='default'))
        ArticleFile.close()
        
        ArticleView.Article.updatePublish()
        
        Articles = model.Article.select()
        return dict(articles=Articles)